<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';

import { fetchUserData } from '@/api';
import TableCustom from '@/components/table-custom.vue';

import TableSearch from '@/components/table-search.vue';
import type { FormOptionList } from '@/types/form-option';
import type { User } from '@/types/user';
import { ElMessage } from 'element-plus';

const query = reactive({ name: '' });
const searchOtp = ref<FormOptionList[]>([{ type: 'input', label: '用户名：', prop: 'name' }]);

const handleSearch = () => {
  changePage(1);
};

const changePage = (val: number) => {
  page.index = val;
  getData();
};
const tableData = ref<User[]>([]);
const allUsers = ref<User[]>([]); // 存储所有用户数据
const getData = async () => {
  // 只在第一次加载时获取所有数据
  if (allUsers.value.length === 0) {
    const res = await fetchUserData();
    allUsers.value = res.data.data.list;
    page.total = res.data.data.pageTotal;
  }

  // 根据搜索条件过滤数据
  let filteredData = [...allUsers.value];

  // 如果有搜索条件，进行过滤
  if (query.name) {
    filteredData = filteredData.filter(user =>
      user.name.toLowerCase().includes(query.name.toLowerCase())
    );
  }

  // 更新总数量
  page.total = filteredData.length;

  // 根据当前页和页面大小计算显示的数据
  const start = (page.index - 1) * page.size;
  const end = start + page.size;
  tableData.value = filteredData.slice(start, end);
};

getData();
// console.log('tableData', tableData);
const page = reactive({ index: 1, size: 10, total: 0 });
// 表格相关
let columns = ref([
  { type: 'index', label: '序号', width: 55, align: 'center' },
  { prop: 'name', label: '用户名' },
  { prop: 'phone', label: '手机号' },
  { prop: 'role', label: '角色' },
  { prop: 'operator', label: '操作' }, // 移除了固定宽度，让它占满剩余空间
]);
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: {},
});
const handleView = (row: any) => {
  viewData.value.row = { ...row };
  viewData.value.list = [
    {
      prop: 'id',
      label: '用户ID',
    },
    {
      prop: 'name',
      label: '用户名',
    },
    {
      prop: 'password',
      label: '密码',
    },
    {
      prop: 'email',
      label: '邮箱',
    },
    {
      prop: 'phone',
      label: '电话',
    },
    {
      prop: 'role',
      label: '角色',
    },
    {
      prop: 'date',
      label: '注册日期',
    },
  ];
  visible1.value = true;
};
// 删除相关
const handleDelete = (row: any) => {
  ElMessage.success('删除成功');

  // 从所有用户数据中删除
  const index = allUsers.value.findIndex(user => user.id === row.id);
  if (index > -1) {
    allUsers.value.splice(index, 1);
    page.total = allUsers.value.length;

    // 重新计算当前页数据
    const start = (page.index - 1) * page.size;
    const end = start + page.size;
    tableData.value = allUsers.value.slice(start, end);

    // 如果当前页没有数据且不是第一页，则回到上一页
    if (tableData.value.length === 0 && page.index > 1) {
      changePage(page.index - 1);
    }
  }
};

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = (row: any) => {
  rowData.value = { ...row };
  isEdit.value = true;
  visible.value = true;
};
console.log('tableData', tableData);
</script>

<template>
  <div>
    <TableSearch :query="query" :options="searchOtp" :search="handleSearch" />
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.index"
        :pageSize="page.size"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :changePage="changePage"
        :editFunc="handleEdit"
      >
        <template #toolbarBtn>
          <el-button type="warning" @click="visible = true">
            <el-icon><circle-plus-filled /></el-icon>
            <span>新增</span>
          </el-button>
        </template>
      </TableCustom>
    </div>
  </div>
</template>

<style lang="scss" scoped>
//
</style>
